package com.eascs.pay.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.controller.PayMentController;
import com.eascs.admin.o2o.internal.dao.WfTypeStatusDao;
import com.eascs.admin.o2o.internal.entity.WfTypeStatus;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.pay.dao.O2oPayDao;
import com.eascs.pay.entity.O2oPayEntity;
import com.eascs.pay.form.O2oPayForm;
import com.eascs.pay.service.O2oPayService;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


//@SuppressWarnings("rawtypes")
@Service
public class O2oPayServiceImpl implements O2oPayService {

	@Autowired
	O2oPayDao payDao;
	
	@Autowired
	O2oLoanUserService o2oLoanUserService;
	@Reference
	private WorkFlowService workFlowService;
	@Autowired
	private WfTypeStatusDao wfTypeStatusDao;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Value("${o2o.admin.service}")
	String url;
	
	private static final Logger logger = LoggerFactory.getLogger(PayMentController.class);
	
	private static Logger log = LoggerFactory.getLogger(O2oPayServiceImpl.class);
	
	public PageResult<Object[]> findByPage(SqlPageQuery<Object[]> pageQuery) {

		return payDao.findDataWithPage(pageQuery);
	}
	
	public PageResult<Object[]> findByPage(O2oPayForm o2oPayForm) {
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, o2oPayForm.getPageSize(), o2oPayForm.getPageIndex());
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT OP.ID,OP.LOANAPPLY_BILLCODE,OP.BILL_CODE,OP.BORROWER_NAME,CONCAT(y.ltd_code,'-',y.ltd_name) as PLATFORM_NAME");
		sql.append(",y.bank_amount/10000,OP.LOAN_TERM,OP.PAYEE_NAME,OP.PAY_TYPE,OP.BILL_STATUS,op.create_time ");
		sql.append(" FROM O2O_PAY OP LEFT JOIN o2o_loanapply y on y.bill_code=op.loanapply_billcode WHERE /**DATA_PERMISSION(OP.PLATFORM)**/  1=1 ");
		if (!StringUtil.isEmpty(o2oPayForm.getBillCode())) {
			sql.append(" AND OP.bill_code LIKE ?");
			pageQuery.addLikeParam(o2oPayForm.getBillCode());
		}
		if (!StringUtil.isEmpty(o2oPayForm.getLoanapplybillcode())) {
			sql.append(" AND OP.LOANAPPLY_BILLCODE LIKE ?");
			pageQuery.addLikeParam(o2oPayForm.getLoanapplybillcode());
		}
		if (!StringUtil.isEmpty(o2oPayForm.getBorrowerName())) {
			sql.append(" AND OP.BORROWER_NAME LIKE ?");
			pageQuery.addLikeParam(o2oPayForm.getBorrowerName());
		}
		if (!StringUtil.isEmpty(o2oPayForm.getPayType())) {
			sql.append(" AND OP.PAY_TYPE = ?");
			pageQuery.addParam(o2oPayForm.getPayType());
		}
		if (!StringUtil.isEmpty(o2oPayForm.getStatus())) {
			sql.append(" AND OP.bill_status = ?");
			pageQuery.addParam(o2oPayForm.getStatus());
		}
		
		if (!StringUtil.isEmpty(o2oPayForm.getCreatestartdate())) {
			sql.append(" AND op.create_time >= ? ");
			pageQuery.addParam(o2oPayForm.getCreatestartdate());
		}
		if (!StringUtil.isEmpty(o2oPayForm.getCreateenddate())) {
			sql.append(" AND op.create_time <=? ");
			pageQuery.addParam(o2oPayForm.getCreateenddate());
		}
		pageQuery.setQuerySql(sql.toString());
		return payDao.findDataWithPage(pageQuery);
	}

	@Override
	public O2oPayEntity findById(String id) {
		return payDao.getById(O2oPayEntity.class, id);
	}
	
	public O2oPayEntity findDetailByBillCode(String billCode) {
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT OP.ID,OP.LOANAPPLY_BILLCODE,OP.BILL_CODE,OP.BORROWER_NAME,OL.LTD_NAME AS PLATFORM,OP.LOAN_AMOUNT,OP.LOAN_TERM,OP.PAYEE_NAME,OP.PAY_TYPE ");
		sql.append(" ,OP.BORROWERID_TYPE,OLU.DOCUMENT_NO AS BORROWERID,OP.COLLECTION_ACCOUNT,OP.PAY_AMOUNT,OP.COLLECTION_BANK_NAME,OP.LOANAPPLYID,OP.BILL_STATUS ");
		sql.append(" ,OP.COLLECTION_BANK_ADDRESS,OP.REMARK,OP.PAY_REMARK FROM O2O_PAY OP JOIN O2O_LOANAPPLY OL ON OL.LOANAPPLY_NO = OP.LOANAPPLYID ");
		sql.append(" JOIN O2O_LOAN_USER OLU ON OLU.LOAN_ID=OP.BORROWERID WHERE OP.LOANAPPLY_BILLCODE = ? ");
		return payDao.findEntity(sql.toString(), O2oPayEntity.class, billCode);
	}
	

	public O2oPayEntity findDetailByOaBillCode(String billCode) {
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT * FROM O2O_PAY OP WHERE OP.LOANAPPLY_BILLCODE = ? ");
		return payDao.findEntity(sql.toString(), O2oPayEntity.class, billCode);
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               根据终端贷贷款单号查询直贷和垫付多少笔（列表）---【查借款金额 OP.LOAN_AMOUNT】
	 *               </p>
	 * @author CXW
	 * @date 2016年10月27日 上午11:13:52
	 * @version V1.0
	 * @param billCode 终端贷贷款单号
	 */
	public List<O2oPayEntity> findByBillCodeList(String billCode) {
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT OP.LOANAPPLY_BILLCODE,OP.BILL_CODE,OP.BORROWER_NAME,OL.LTD_NAME AS PLATFORM,OP.LOAN_AMOUNT,OP.LOAN_TERM,OP.PAYEE_NAME,OP.PAY_TYPE ");
		sql.append(" ,OP.BORROWERID_TYPE,OLU.DOCUMENT_NO AS BORROWERID,OP.COLLECTION_ACCOUNT,OP.PAY_AMOUNT,OP.COLLECTION_BANK_NAME,OP.LOANAPPLYID,OP.BILL_STATUS ");
		sql.append(" ,OP.COLLECTION_BANK_ADDRESS,OP.REMARK,OP.PAY_REMARK FROM O2O_PAY OP JOIN O2O_LOANAPPLY OL ON OL.LOANAPPLY_NO = OP.LOANAPPLYID ");
		sql.append(" JOIN O2O_LOAN_USER OLU ON OLU.LOAN_ID=OP.BORROWERID AND OP.LOANAPPLYID=OLU.LOANAPPLY_NO WHERE OP.BILL_CODE = ? ");
		return payDao.findEntitys(sql.toString(), O2oPayEntity.class, billCode);
	}
	/**
	 * @Description:
	 *               <p>
	 *               根据终端贷贷款单号查询直贷和垫付多少笔（列表）---【查放款金额（银行批复额度）OL.bank_amount as LOAN_AMOUNT】
	 *               </p>
	 * @author CXW
	 * @date 2016年10月27日 上午11:13:52
	 * @version V1.0
	 * @param billCode 终端贷贷款单号
	 */
	public List<O2oPayEntity> findByBillCodeList_OL(String billCode) {
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT OP.LOANAPPLY_BILLCODE,OP.BILL_CODE,OP.BORROWER_NAME,OL.LTD_NAME AS PLATFORM,OL.bank_amount as LOAN_AMOUNT,OP.LOAN_TERM,OP.PAYEE_NAME,OP.PAY_TYPE ");
		sql.append(" ,OP.BORROWERID_TYPE,CONCAT( LEFT (OLU.DOCUMENT_NO, 3), '****', RIGHT (OLU.DOCUMENT_NO, 3)) AS BORROWERID,OP.COLLECTION_ACCOUNT,OP.PAY_AMOUNT,OP.COLLECTION_BANK_NAME,OP.LOANAPPLYID,OP.BILL_STATUS ");
		sql.append(" ,OP.COLLECTION_BANK_ADDRESS,OP.REMARK,OP.PAY_REMARK FROM O2O_PAY OP JOIN O2O_LOANAPPLY OL ON OL.LOANAPPLY_NO = OP.LOANAPPLYID ");
		sql.append(" JOIN O2O_LOAN_USER OLU ON OLU.LOAN_ID=OP.BORROWERID AND OP.LOANAPPLYID=OLU.LOANAPPLY_NO WHERE OP.BILL_CODE = ? ");
		return payDao.findEntitys(sql.toString(), O2oPayEntity.class, billCode);
	}
	/**
	 * 消息通知
	 */
	@Override
	@Transactional(transactionManager = "o2oTransactionManager")
	public int updateEntityById(O2oPayEntity o2oPayEntity) {
		return payDao.updateById(o2oPayEntity);

	}
	
	/**
	 * 更新动态表单
	 * @param o2oPayEntity
	 * @return
	 */
//	@Transactional(transactionManager = "o2oTransactionManager")
//	public int updateEntityById(O2oPayEntity o2oPayEntity) {
//		return payDao.updateById(o2oPayEntity);
//		
//	}

	@Override
	public int deleteEntityById(O2oPayEntity o2oPayEntity) {
		o2oPayEntity = findById(o2oPayEntity.getId());
		o2oPayEntity.setIsdel("Y");
		return payDao.updateById(o2oPayEntity);
	}

	@Override
	@Transactional(transactionManager = "o2oTransactionManager")
	public int saveEntityById(O2oPayEntity o2oPayEntity) {
		o2oPayEntity.setId(UuidUtil.generateShortUuid(4));
		o2oPayEntity.setIsdel("N");
		return payDao.insert(o2oPayEntity);
	}

	@Override
	public boolean isHavePayFlow(O2oPayEntity o2oPayEntity ) {
		// StringBuffer sql = new StringBuffer(" SELECT count(1) FROM o2o_pay OL where 1=1 and OL.bill_status in('RUN','CLO') ");
		StringBuffer sql = new StringBuffer(" SELECT count(1) FROM o2o_pay OL where 1=1 and OL.bill_status in('RUN','NEW') ");
		if(StringUtil.isNotBlank(o2oPayEntity.getLoanapplyBillcode())){
			sql.append(" and OL.loanapply_billcode =  '" +o2oPayEntity.getLoanapplyBillcode()+"'" );
		}
		if(StringUtil.isNotBlank(o2oPayEntity.getIsdel())){
			sql.append(" and OL.isdel =  '" +o2oPayEntity.getIsdel()+"'" );
		}
//		if(StringUtil.isNotBlank(o2oPayEntity.getBillStatus())){
//			sql.append(" and OL.bill_status <>  '" +o2oPayEntity.getBillStatus()+"'" );
//		}
		if(StringUtil.isNotBlank(o2oPayEntity.getPayType())){
			sql.append(" and OL.pay_type =  '" +o2oPayEntity.getPayType()+"'" );
		}
		int count = payDao.findInteger(sql.toString());
		if(count>0){
			return true;
		}else{
			return false;
		}
	}
	
	@Override
	public boolean isHaveRUNPayFlow(O2oPayEntity o2oPayEntity) {
		// StringBuffer sql = new StringBuffer(" SELECT count(1) FROM o2o_pay OL where 1=1 and OL.bill_status in('RUN','CLO') ");
		StringBuffer sql = new StringBuffer(" SELECT count(1) FROM o2o_pay OL where 1=1 and OL.bill_status= 'RUN' ");
		if(StringUtil.isNotBlank(o2oPayEntity.getLoanapplyBillcode())){
			sql.append(" and OL.loanapply_billcode =  '" +o2oPayEntity.getLoanapplyBillcode()+"'" );
		}
		if(StringUtil.isNotBlank(o2oPayEntity.getIsdel())){
			sql.append(" and OL.isdel =  '" +o2oPayEntity.getIsdel()+"'" );
		}
//		if(StringUtil.isNotBlank(o2oPayEntity.getBillStatus())){
//			sql.append(" and OL.bill_status <>  '" +o2oPayEntity.getBillStatus()+"'" );
//		}
		if(StringUtil.isNotBlank(o2oPayEntity.getPayType())){
			sql.append(" and OL.pay_type =  '" +o2oPayEntity.getPayType()+"'" );
		}
		int count = payDao.findInteger(sql.toString());
		if(count>0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 根据贷款编号（主表id）查询对象O2oPayEntity
	 * @param loanapplyid
	 * @return
	 */
	public O2oPayEntity findEntityByLoanapplyId(String loanapplyid) {
		String sql = "SELECT OP.* FROM O2O_PAY OP WHERE OP.LOANAPPLYID = ? AND OP.BILL_STATUS='NEW'";
		return payDao.findEntity(sql, O2oPayEntity.class, loanapplyid);
	}
	
	/**
	 * 付款表单check
	 * @param loanapplyid
	 * @return
	 */
	public int getCheckCount(String loanapplyid){
		String sql = "SELECT COUNT(OL.PAYEE_NAME) FROM O2O_PAY OL WHERE  OL.LOANAPPLYID = ? ";
		return payDao.findInteger(sql, loanapplyid);
	}
	

	@Override
	@Transactional("o2oTransactionManager")
	public int insertPayByEntity(O2oLoanapplyEntity o2oLoanapplyEntity,String payType,CustomerBasicInfoEntity basicEntity) {
		// TODO Auto-generated method stub
		//O2oLoanapplyContinueEntity o2oLoanapplyContinueEntity =  o2oLoanapplyService.findContinueById(o2oLoanapplyEntity.getLoanapplyNo());
		O2oPayEntity o2oPayEntity = new O2oPayEntity();
		o2oPayEntity.setPayType(payType);//自动启动的都是直贷类型
		if(payType.equals(StatusContexts.PAY_TYPE_DF)){//垫付
			o2oPayEntity.setLoanapplyid(o2oLoanapplyEntity.getLoanapplyNo());
			o2oPayEntity.setLoanapplyBillcode(o2oLoanapplyEntity.getBillCode());
			o2oPayEntity.setBillCode(o2oLoanapplyEntity.getBillCode());
		}
		if(payType.equals(StatusContexts.PAY_TYPE_ZD)){
			o2oPayEntity.setLoanapplyid(o2oLoanapplyEntity.getLoanapplyNo());
			o2oPayEntity.setLoanapplyBillcode(o2oLoanapplyEntity.getBillCode());
			o2oPayEntity.setBillCode(o2oLoanapplyEntity.getContinueLoanParenNo());
		}
		
		o2oPayEntity.setBorrowerId(o2oLoanapplyEntity.getLoanId()); //借款人id
		o2oPayEntity.setCreateDate(new Date());
		o2oPayEntity.setCreator(o2oLoanapplyEntity.getCreatRo());
		o2oPayEntity.setIsdel(StatusContexts.O2O_NO);
		o2oPayEntity.setLoanTerm(String.valueOf(o2oLoanapplyEntity.getLoanTerm())); 
		o2oPayEntity.setLoanAmount(o2oLoanapplyEntity.getLoanaMount());
		o2oPayEntity.setPlatform(o2oLoanapplyEntity.getLtd()); //经营单位id
		o2oPayEntity.setPlatformName(o2oLoanapplyEntity.getLtdName());
		o2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);  //新建的默认是new状态
		//直贷的提交人默认取经办人
		o2oPayEntity.setSubmitUser(o2oLoanapplyEntity.getOperatorNo());
		o2oPayEntity.setSubmitTime(new Date());
		o2oPayEntity.setResourseFrom(o2oLoanapplyEntity.getRepaymentSource());
		//根据借款人id获取借款人信息
		O2oLoanUserEntity loaner =  o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(), o2oLoanapplyEntity.getLoanapplyNo());
		if (loaner != null) {
			o2oPayEntity.setBorrowerName(loaner.getUserFullName()); // 借款人姓名
			o2oPayEntity.setBorroweridType(loaner.getDocumentType()); // 证件类型
		} else {
			if (null != basicEntity) {
				o2oPayEntity.setBorrowerName(basicEntity.getCustomerName()); // 借款人姓名
				o2oPayEntity.setBorroweridType(basicEntity.getIdType()); // 证件类型
			}
		}
		int i = payDao.insert(o2oPayEntity);

		if(i<0){
			log.info("保存付款数据失败");
		}else{
			// updateWftypeStatus(o2oPayEntity.getLoanapplyid(), StatusContexts.WFTYPE_PAY);
			log.info("保存付款数据成功");
		}
		return i;
	}
	
	@Override
	@Transactional("o2oTransactionManager")
	public int insertPayByEntityFx(O2oLoanapplyEntity o2oLoanapplyEntity,String payType,String payFkType,CustomerBasicInfoEntity basicEntity) {
		// TODO Auto-generated method stub
		//O2oLoanapplyContinueEntity o2oLoanapplyContinueEntity =  o2oLoanapplyService.findContinueById(o2oLoanapplyEntity.getLoanapplyNo());
		O2oPayEntity o2oPayEntity = new O2oPayEntity();
		o2oPayEntity.setPayType(payType);//自动启动的都是直贷类型
		if(payType.equals(StatusContexts.PAY_TYPE_DF)){//垫付
			o2oPayEntity.setLoanapplyid(o2oLoanapplyEntity.getLoanapplyNo());
			o2oPayEntity.setLoanapplyBillcode(o2oLoanapplyEntity.getBillCode());
			o2oPayEntity.setBillCode(o2oLoanapplyEntity.getBillCode());
		}
		if(payType.equals(StatusContexts.PAY_TYPE_ZD)){
			o2oPayEntity.setLoanapplyid(o2oLoanapplyEntity.getLoanapplyNo());
			o2oPayEntity.setLoanapplyBillcode(o2oLoanapplyEntity.getBillCode());
			o2oPayEntity.setBillCode(o2oLoanapplyEntity.getContinueLoanParenNo());
		}
		o2oPayEntity.setPayFkType(payFkType);
		o2oPayEntity.setBorrowerId(o2oLoanapplyEntity.getLoanId()); //借款人id
		o2oPayEntity.setCreateDate(new Date());
		o2oPayEntity.setCreator(o2oLoanapplyEntity.getCreatRo());
		o2oPayEntity.setIsdel(StatusContexts.O2O_NO);
		o2oPayEntity.setLoanTerm(String.valueOf(o2oLoanapplyEntity.getLoanTerm())); 
		o2oPayEntity.setLoanAmount(o2oLoanapplyEntity.getLoanaMount());
		o2oPayEntity.setPlatform(o2oLoanapplyEntity.getLtd()); //经营单位id
		o2oPayEntity.setPlatformName(o2oLoanapplyEntity.getLtdName());
		o2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);  //新建的默认是new状态
		//直贷的提交人默认取经办人
		o2oPayEntity.setSubmitUser(o2oLoanapplyEntity.getOperatorNo());
		o2oPayEntity.setSubmitTime(new Date());
		o2oPayEntity.setResourseFrom(o2oLoanapplyEntity.getRepaymentSource());
		//根据借款人id获取借款人信息
		O2oLoanUserEntity loaner =  o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(), o2oLoanapplyEntity.getLoanapplyNo());
		if (loaner != null) {
			o2oPayEntity.setBorrowerName(loaner.getUserFullName()); // 借款人姓名
			o2oPayEntity.setBorroweridType(loaner.getDocumentType()); // 证件类型
		} else {
			if (null != basicEntity) {
				o2oPayEntity.setBorrowerName(basicEntity.getCustomerName()); // 借款人姓名
				o2oPayEntity.setBorroweridType(basicEntity.getIdType()); // 证件类型
			}
		}
		int i = payDao.insert(o2oPayEntity);

		if(i<0){
			log.info("保存付款数据失败");
		}else{
			// updateWftypeStatus(o2oPayEntity.getLoanapplyid(), StatusContexts.WFTYPE_PAY);
			log.info("保存付款数据成功");
		}
		return i;
	}
	
	
	@Override
	@Transactional("o2oTransactionManager")
	public int updatePayByEntityFx(O2oLoanapplyEntity o2oLoanapplyEntity,String payType,String payFkType,CustomerBasicInfoEntity basicEntity) {
		// TODO Auto-generated method stub
		//O2oLoanapplyContinueEntity o2oLoanapplyContinueEntity =  o2oLoanapplyService.findContinueById(o2oLoanapplyEntity.getLoanapplyNo());
		O2oPayEntity o2oPayEntity = new O2oPayEntity();
		o2oPayEntity.setPayType(payType);//自动启动的都是直贷类型
		if(payType.equals(StatusContexts.PAY_TYPE_DF)){//垫付
			o2oPayEntity.setLoanapplyid(o2oLoanapplyEntity.getLoanapplyNo());
			o2oPayEntity.setLoanapplyBillcode(o2oLoanapplyEntity.getBillCode());
			o2oPayEntity.setBillCode(o2oLoanapplyEntity.getBillCode());
		}
		if(payType.equals(StatusContexts.PAY_TYPE_ZD)){
			o2oPayEntity.setLoanapplyid(o2oLoanapplyEntity.getLoanapplyNo());
			o2oPayEntity.setLoanapplyBillcode(o2oLoanapplyEntity.getBillCode());
			o2oPayEntity.setBillCode(o2oLoanapplyEntity.getContinueLoanParenNo());
		}
		o2oPayEntity.setPayFkType(payFkType);
		o2oPayEntity.setBorrowerId(o2oLoanapplyEntity.getLoanId()); //借款人id
		o2oPayEntity.setCreateDate(new Date());
		o2oPayEntity.setCreator(o2oLoanapplyEntity.getCreatRo());
		o2oPayEntity.setIsdel(StatusContexts.O2O_NO);
		o2oPayEntity.setLoanTerm(String.valueOf(o2oLoanapplyEntity.getLoanTerm())); 
		o2oPayEntity.setLoanAmount(o2oLoanapplyEntity.getLoanaMount());
		o2oPayEntity.setPlatform(o2oLoanapplyEntity.getLtd()); //经营单位id
		o2oPayEntity.setPlatformName(o2oLoanapplyEntity.getLtdName());
		o2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);  //新建的默认是new状态
		//直贷的提交人默认取经办人
		o2oPayEntity.setSubmitUser(o2oLoanapplyEntity.getOperatorNo());
		o2oPayEntity.setSubmitTime(new Date());
		o2oPayEntity.setResourseFrom(o2oLoanapplyEntity.getRepaymentSource());
		//根据借款人id获取借款人信息
		O2oLoanUserEntity loaner =  o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(), o2oLoanapplyEntity.getLoanapplyNo());
		if (loaner != null) {
			o2oPayEntity.setBorrowerName(loaner.getUserFullName()); // 借款人姓名
			o2oPayEntity.setBorroweridType(loaner.getDocumentType()); // 证件类型
		} else {
			if (null != basicEntity) {
				o2oPayEntity.setBorrowerName(basicEntity.getCustomerName()); // 借款人姓名
				o2oPayEntity.setBorroweridType(basicEntity.getIdType()); // 证件类型
			}
		}
		//int i = payDao.updateById(o2oPayEntity);
		int i = 1;

		if(i<0){
			log.info("保存付款数据失败");
		}else{
			// updateWftypeStatus(o2oPayEntity.getLoanapplyid(), StatusContexts.WFTYPE_PAY);
			log.info("保存付款数据成功");
		}
		return i;
	}
	
	/**
	 * 启动付款流程
	 */
	public ModelResult<Boolean> startPayFlow(O2oLoanapplyEntity o2oLoanapplyEntity, String userName) { // 根据单号去启动流程
	   O2oLoanapplyEntity loan = o2oLoanapplyService.findById(o2oLoanapplyEntity.getLoanapplyNo());
		//获取 o2opay对象
		O2oPayEntity o2oPayEntity = findEntityByLoanapplyId(o2oLoanapplyEntity.getLoanapplyNo());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oPayEntity.getId());
		param.setReferCode(o2oLoanapplyEntity.getBillCode());
		param.setReferUrl(url + "/rpay/pay_approval");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(ProcessTemplate.PROECESS_TYPE_PAY_FQ);  //修改成付费流程编号
		param.setAppliedby(o2oLoanapplyEntity.getOperatorNo());
		param.setAppliedbyName(o2oLoanapplyEntity.getOperatorName());
		param.setOrgNo(o2oLoanapplyEntity.getLtd());
		if(StringUtil.isNotBlank(loan.getBankLoanName())&&o2oPayEntity.getPayType().equals("DF")){
			if ("GACZ".equals(loan.getBankLoanName())) {
				List<String> deleteParmList=new ArrayList<String>();
				deleteParmList.add("xindai");//信贷经理
				deleteParmList.add("qqww");//平台总经理
				deleteParmList.add("oio");//省区风控经理（省区金融专员）
				deleteParmList.add("5ffff");//省区金融总监（省区财务总监）
				deleteParmList.add("zbfxzjj");//总部风险总监
				deleteParmList.add("FK_GBZJBMFK");//总部资金部门付款
				param.setExcludeNodeCodeList(deleteParmList);
			}else{
				List<String> deleteParmList=new ArrayList<String>();
				deleteParmList.add("xindai");//信贷经理
				deleteParmList.add("qqww");//平台总经理
				deleteParmList.add("oio");//省区风控经理（省区金融专员）
	//			deleteParmList.add("5ffff");//省区金融总监（省区财务总监）
				deleteParmList.add("zbfxzjj");//总部风险总监
	//			deleteParmList.add("FK_GBZJBMFK");//总部资金部门付款
				param.setExcludeNodeCodeList(deleteParmList);
			}

		}
		log.info("提交人：【{}，{},{}】", o2oLoanapplyEntity.getOperatorNo(), o2oLoanapplyEntity.getOperatorName(), o2oLoanapplyEntity.getLtd());
		//map
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		//roleUserMap.put(StatusContexts.LOAN_TYPE_PTJL_ROLE, Arrays.asList(o2oLoanapplyEntity.getOperatorNo()));  //第二个节点，动态指定经办人
		roleUserMap.put(StatusContexts.LOAN_TYPE_LRSJFK_ROLE, Arrays.asList(o2oLoanapplyEntity.getOperatorNo())); 		//第六个节点，动态指定提交人
		param.setRoleUserMap(roleUserMap);
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(userName);
		/*appliedDes.append("，付款金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
		appliedDes.append(df.format(o2oPayEntity.getPayAmount().doubleValue()));*/
		param.setAppliedDes(appliedDes.toString());
		logger.info("启动付款流程，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oLoanapplyEntity.getLoanapplyNo(),o2oLoanapplyEntity.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),o2oLoanapplyEntity.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		return modelResult;
	}
	
	
	/**
	 * 启动付款流程FX
	 */
	public ModelResult<Boolean> startPayFlowFx(O2oLoanapplyEntity o2oLoanapplyEntity, String userName) { // 根据单号去启动流程
	   O2oLoanapplyEntity loan = o2oLoanapplyService.findById(o2oLoanapplyEntity.getLoanapplyNo());
		//获取 o2opay对象
		O2oPayEntity o2oPayEntity = findEntityByLoanapplyId(o2oLoanapplyEntity.getLoanapplyNo());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oPayEntity.getId());
		param.setReferCode(o2oLoanapplyEntity.getBillCode());
		param.setReferUrl(url + "/rpay/pay_approval");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(ProcessTemplate.PROECESS_TYPE_PAY_FQ);  //修改成付费流程编号
		param.setAppliedby(o2oLoanapplyEntity.getOperatorNo());
		param.setAppliedbyName(o2oLoanapplyEntity.getOperatorName());
		param.setOrgNo(o2oLoanapplyEntity.getLtd());
		if (o2oPayEntity.getPayFkType().equals(StatusContexts.PAYMENT_TYPE_XF)) {
			List<String> deleteParmList=new ArrayList<String>();
			deleteParmList.add("xindai");//信贷经理
			deleteParmList.add("qqww");//平台总经理
			deleteParmList.add("oio");//省区风控经理（省区金融专员）
			//deleteParmList.add("5ffff");//省区金融总监（省区财务总监）
			deleteParmList.add("zbfxzjj");//总部风险总监
			deleteParmList.add("FK_GBZJBMFK");//总部资金部门付款
			param.setExcludeNodeCodeList(deleteParmList);
		}else{
			List<String> deleteParmList=new ArrayList<String>();
			deleteParmList.add("xindai");//信贷经理
			deleteParmList.add("qqww");//平台总经理
			deleteParmList.add("oio");//省区风控经理（省区金融专员）
//			deleteParmList.add("5ffff");//省区金融总监（省区财务总监）
			deleteParmList.add("zbfxzjj");//总部风险总监
//			deleteParmList.add("FK_GBZJBMFK");//总部资金部门付款
			param.setExcludeNodeCodeList(deleteParmList);
		}

		log.info("提交人：【{}，{},{}】", o2oLoanapplyEntity.getOperatorNo(), o2oLoanapplyEntity.getOperatorName(), o2oLoanapplyEntity.getLtd());
		//map
		Map<String, List<String>> roleUserMap = new HashMap<>();  //指定流程节点由谁经办
		//roleUserMap.put(StatusContexts.LOAN_TYPE_PTJL_ROLE, Arrays.asList(o2oLoanapplyEntity.getOperatorNo()));  //第二个节点，动态指定经办人
		roleUserMap.put(StatusContexts.LOAN_TYPE_LRSJFK_ROLE, Arrays.asList(o2oLoanapplyEntity.getOperatorNo())); 		//第六个节点，动态指定提交人
		param.setRoleUserMap(roleUserMap);
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(userName);
		/*appliedDes.append("，付款金额:");
		java.text.DecimalFormat df=new java.text.DecimalFormat("0.00"); //格式化，保留两位小数 
		appliedDes.append(df.format(o2oPayEntity.getPayAmount().doubleValue()));*/
		param.setAppliedDes(appliedDes.toString());
		logger.info("启动付款流程，参数有贷款id：【{}】，贷款编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", 
				o2oLoanapplyEntity.getLoanapplyNo(),o2oLoanapplyEntity.getBillCode(),ProcessTemplate.SYSTEM_MODULE_O2O,param.getProcessType(),o2oLoanapplyEntity.getLtd(),appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		return modelResult;
	}
	
	/**
	 * 插入流程主状态
	 * 
	 * @param wfTypeStatus
	 * @param notifyParam
	 * 
	 */
	@Transactional("o2oTransactionManager")
	public void updateWftypeStatus(String o2oLoanapplyNo, String wfType) {
		WfTypeStatus wfTypeStatus = wfTypeStatusDao.getByLoanapplyNoAndWfType(o2oLoanapplyNo, wfType);
		Date date = new Date();
		if (wfTypeStatus == null) {
			log.info("ReferId:[{}],插入流程主状态数据", o2oLoanapplyNo);
			WfTypeStatus wfTypeStatus_ = new WfTypeStatus();
			wfTypeStatus_.setLoapplyNo(o2oLoanapplyNo);
			wfTypeStatus_.setWfType(wfType);
			wfTypeStatus_.setWfDate(date);
			wfTypeStatus_.setWfStatus(StatusContexts.WFTYPE_STATUS_RUN);
			wfTypeStatus_.setStartDate(date);
			int effectRow = wfTypeStatusDao.insert(wfTypeStatus_);
			if (effectRow <= 0) {
				log.info("ReferId:[{}],插入工作流状态表失败", o2oLoanapplyNo);
				throw new RuntimeException("插入工作流状态表失败");
			}
			log.info("ReferId:[{}],插入工作流状态表成功", o2oLoanapplyNo);
		} else {
			wfTypeStatus.setWfStatus(StatusContexts.WFTYPE_STATUS_RUN);
			wfTypeStatus.setWfType(wfType);
//			wfTypeStatus.setWfDate(date);
			wfTypeStatus.setStartDate(date);
			int effectRow = wfTypeStatusDao.updateById(wfTypeStatus);
			if (effectRow <= 0) {
				log.info("ReferId:[{}],插入工作流状态表失败", o2oLoanapplyNo);
				throw new RuntimeException("ReferId:[{}],更新工作流状态表失败" + o2oLoanapplyNo);
			}
		}
		log.info("ReferId:[{}],更新工作流状态表成功", o2oLoanapplyNo);
	}


}
